package com.alibaba.shopping_seckill_service.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedissonLock
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/23 16:50
 */
@Component
public class RedissonLock {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 加锁
     * @param key 锁的名字(商品ID)
     * @param expireTime 过期时间，防止长时间占用
     * @return
     */
    public Boolean lock(String key,Integer expireTime){
        RLock lock = redissonClient.getLock(key);
        try {
            // 尝试获取锁，如果没有别人占用这把锁， 则拿到锁
            return lock.tryLock(expireTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // 没有拿到锁证明别人占用，中断当前线程
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void unlock(String key){
        RLock lock = redissonClient.getLock("lockL:" + key);
        if (lock.isLocked()){
            // 释放锁
            lock.unlock();
        }
    }
}




